@extends('buy_process.master')

@section('title')
    支付-Craft
@endsection

@section('link')
    <link rel="stylesheet" href="{{asset('css/buy_process/pay.css')}}">
@endsection

@section('headerTitle')
    支付
@endsection

@section('content')
    <section id="app" style="margin-top: 50px;padding-bottom: 50px">
        <el-row>
            <el-col :span="18" :offset="3">
                <el-row>
                    <el-col :span="24">
                        <el-steps :active="orderStatus">
                            <el-step title="下单" icon="el-icon-tickets"></el-step>
                            <el-step title="支付" icon="el-icon-coin"></el-step>
                            <el-step title="下单成功" icon="el-icon-circle-check"></el-step>
                        </el-steps>
                    </el-col>
                </el-row>

                <el-row :gutter="50" style="margin-top: 50px">

                    <el-col :span="10">
                        <el-image class="crafts-item-img" :src="'{{asset('/')}}'+order.imgUrl"
                                  @click="detail(order.goods_id)"></el-image>
                    </el-col>


                    <el-col :span="11" :offset="1" class="orderInfo">
                        <el-form :model="order" label-position="top">
                            <el-form-item label="收货人地址" class="address">
                                <el-row>
                                    <div class="useAddress-item">@{{ order.name }}</div>
                                    <div class="useAddress-item">@{{ order.phone }}</div>
                                    <div class="useAddress-item">
                                        @{{ order.province }} |
                                        @{{ order.city }} |
                                        @{{ order.county }} |
                                        @{{ order.region }}
                                    </div>
                                    <div class="useAddress-item">@{{ order.detail_address }}</div>
                                </el-row>
                                <el-row :gutter="20" style="margin-top: 10px">
                                    <el-col :span="24">
                                        <el-button @click="openDrawer">
                                            修改地址
                                        </el-button>
                                    </el-col>
                                </el-row>
                            </el-form-item>

                            <el-form-item label="作品信息">
                                <div>@{{ order.goods_name }}</div>
                                <div>@{{ order.author }}</div>
                                <div>￥ @{{ order.price }} | @{{ order.size }}</div>
                            </el-form-item>

                            <el-form-item label="备注">
                                <span>
                                    @{{ order.remark }}
                                </span>
                            </el-form-item>


                            <el-form-item label="合计">
                                <div>￥ @{{ order.price }}</div>
                            </el-form-item>

                            <el-form-item>
                                <el-button @click="pay" class="btn_submit_order" :disabled="payDisabled">
                                    支付 @{{ clockText }}
                                </el-button>
                            </el-form-item>
                        </el-form>
                    </el-col>
                </el-row>
            </el-col>
        </el-row>


        <el-drawer
            :with-header="false"
            direction="rtl"
            :modal="false"
            ref="drawer"
            :visible.sync="changeAddressDrawer"
            class="drawer_address">

            <el-form class="select_box" label-width="150px"
                     :model="selectAddress" ref="form-address" :rules="rules"
                     :hide-required-asterisk="true">
                <el-form-item label="收货人" prop="name">
                    <el-input v-model="selectAddress.name" placeholder="收货人姓名"></el-input>
                </el-form-item>

                <el-form-item label="联系电话" prop="phone">
                    <el-input v-model="selectAddress.phone" placeholder="收货人联系电话"></el-input>
                </el-form-item>


                <el-form-item label="请选择省市/地区" prop="selectProvince">
                    <el-select v-model="selectAddress.selectProvince" placeholder="请选择省市/地区" @change="provinceChange">
                        <el-option
                            v-for="item in provinces"
                            :key="item.province_id"
                            :label="item.province_name"
                            :value="item.province_id">
                        </el-option>
                    </el-select>
                </el-form-item>


                <el-form-item label="请选择城市/地区" prop="selectCity">
                    <el-select v-model="selectAddress.selectCity" placeholder="请选择城市/地区" :disabled="cityEnable"
                               @change="cityChange">
                        <el-option
                            v-for="item in cities"
                            :key="item.city_id"
                            :label="item.city_name"
                            :value="item.city_id">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="请选择城镇/地区" prop="selectCounty">
                    <el-select v-model="selectAddress.selectCounty" placeholder="请选择城镇/地区" :disabled="countyEnable"
                               @change="countyChange">
                        <el-option
                            v-for="item in counties"
                            :key="item.county_id"
                            :label="item.county_name"
                            :value="item.county_id">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="请选择地区" prop="selectRegion">
                    <el-select v-model="selectAddress.selectRegion" placeholder="请选择地区" :disabled="regionEnable"
                               @change="regionChange">
                        <el-option
                            v-for="item in regions"
                            :key="item.town_id"
                            :label="item.town_name"
                            :value="item.town_id">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="详细地址" prop="detailAddress">
                    <el-input class="inp-detailed-address" type="textarea" placeholder="请填写详细地址"
                              v-model="selectAddress.detailAddress">
                    </el-input>
                </el-form-item>

                <el-form-item>
                    <el-button @click="closeDrawer" class="btn_close">关 闭</el-button>
                    <el-button @click="drawerSubmit" class="btn_confirm">确 定</el-button>
                </el-form-item>

            </el-form>

        </el-drawer>
    </section>
@endsection

@section('js')
    <script>
        var clock;
        var hasTime;
        var app = new Vue({
                el: '#app',
                created() {
                    this.openTimer();
                },
                data() {
                    var checkPhone = (rule, value, callback) => {
                        const reg = /^1[3|4|5|7|8|9][0-9]\d{8}$/;
                        if (value === '') {
                            callback(new Error('请输入电话号码'));
                        } else if (!reg.test(value)) {
                            callback(new Error('请输入正确的11位手机号码'));
                        } else {
                            callback();
                        }
                    };
                    return {
                        order: (@json($data)).order,
                        orderStatus: 1,
                        changeAddressDrawer: false,
                        clock: null,
                        clockText: '',
                        payDisabled: false,

                        provinces: (@json($data)).provinces,
                        cities: [],
                        counties: [],
                        regions: [],
                        cityEnable: true,
                        countyEnable: true,
                        regionEnable: true,
                        selectAddress: {
                            phone: '',
                            name: '',
                            selectProvince: '',
                            selectCity: '',
                            selectCounty: '',
                            selectRegion: '',
                            detailAddress: '',
                        },
                        selectProvinceName: '',
                        selectCityName: '',
                        selectCountyName: '',
                        selectRegionName: '',
                        rules: {
                            name: [{required: true, message: '收货人不能为空', trigger: ['blur', 'change']}],
                            phone: [{validator: checkPhone, trigger: ['blur', 'change']}],
                            selectProvince: [{required: true, message: '请选择省市/地区', trigger: ['blur', 'change']}],
                            selectCity: [{required: true, message: '请选择城市/地区', trigger: ['blur', 'change']}],
                            selectCounty: [{required: true, message: '请选择城镇/地区', trigger: ['blur', 'change']}],
                            selectRegion: [{required: true, message: '请选择地区', trigger: ['blur', 'change']}],
                            detailAddress: [{required: true, message: '详细地址不能为空', trigger: ['blur', 'change']}],
                        }
                    }
                },
                methods: {
                    //支付
                    pay() {
                        let data = new FormData();
                        data.append('id', this.order.id);
                        data.append('goods_id', this.order.goods_id);
                        data.append('user_id', this.order.user_id);
                        axios.post('/order/pay', data)
                            .then(res => {
                                if (res.data.status_code === 200) {
                                    clearInterval(clock);  //清除定时器
                                    app.noticeSuccess(res.data.message);
                                    setTimeout(function () {
                                        window.location='/order/paySuccess/'+app.order.id;
                                    },1000);
                                } else {
                                    app.openTimer();
                                    app.noticeWarnings(res.data.error);
                                }
                            })
                    },
                    //取消订单
                    cancelOrder() {
                        let data = new FormData();
                        data.append('id', this.order.id);
                        axios.post('/user/myOrder/cancelOrder', data)
                            .then(res => {
                                app.noticeSuccess(res.data.message);
                            })
                            .catch(err => {
                                console.log(err);
                                app.noticeError('取消订单失败,服务器繁忙，请稍后再试！');
                            })
                    },

                    openTimer(){
                        //开启订单倒计时
                        if(this.order.status===0){
                            let now = new Date();
                            let orderD = new Date(this.order.created_at);
                            orderD.setMinutes(orderD.getMinutes() + 15);
                            hasTime = Math.floor((orderD - now) / 1000);
                            clock = setInterval(function () {
                                let minutes=Math.floor(hasTime / 60);
                                let seconds=(hasTime % 60);
                                if(minutes>0){
                                    app.clockText = minutes+ '分' + seconds + '秒';
                                }else{
                                    app.clockText = seconds + '秒';
                                }
                                hasTime--;
                                if (hasTime <= 1) {
                                    app.payDisabled = true;
                                }
                                if (hasTime <= 0) {
                                    app.payDisabled = true;
                                    clearInterval(clock);
                                    app.noticeSuccess('您的订单已超时');
                                    app.cancelOrder();
                                }
                            }, 1000);
                        }
                    },
                    //打开侧边drawer
                    openDrawer() {
                        let item = JSON.parse(JSON.stringify(this.order));
                        app.selectAddress.name = item.name;
                        app.selectAddress.phone = item.phone;
                        app.selectAddress.detailAddress = item.detail_address;
                        app.provinceChange(item.province_id);
                        app.cityChange(item.city_id);
                        app.countyChange(item.county_id);
                        app.selectAddress.selectProvince = item.province_id;
                        app.selectAddress.selectCity = item.city_id;
                        app.selectAddress.selectCounty = item.county_id;
                        app.selectAddress.selectRegion = item.town_id;
                        app.selectAddress.currentId = item.id;
                        app.selectProvinceName = item.province;
                        app.selectCityName = item.city;
                        app.selectCountyName = item.county;
                        app.selectRegionName = item.region;

                        app.changeAddressDrawer = true;
                    },
                    closeDrawer() {
                        app.changeAddressDrawer = false;
                    },
                    drawerSubmit() {
                        let check = false;
                        this.$refs['form-address'].validate(result => {
                            check = result;
                        });
                        if (!check) {
                            this.noticeWarning('请将数据填写完整！');
                            return false;
                        }
                        let data = new FormData();
                        data.append('id', this.order.id);
                        data.append('name', app.selectAddress.name);
                        data.append('phone', app.selectAddress.phone);
                        data.append('town_id', app.selectAddress.selectRegion);
                        data.append('detail_address', this.selectAddress.detailAddress);
                        axios.post('/order/pay/changeOrderAddress', data)
                            .then(res => {
                                if (res.data.status_code === 200) {
                                    app.order.name = app.selectAddress.name;
                                    app.order.phone = app.selectAddress.phone;
                                    app.order.province = app.selectProvinceName;
                                    app.order.city = app.selectCityName;
                                    app.order.county = app.selectCountyName;
                                    app.order.region = app.selectRegionName;
                                    app.order.province_id = app.selectAddress.selectProvince;
                                    app.order.city_id = app.selectAddress.selectCity;
                                    app.order.county_id = app.selectAddress.selectCounty;
                                    app.order.town_id = app.selectAddress.selectRegion;
                                    app.order.detail_address = app.selectAddress.detailAddress;
                                    app.noticeSuccess(res.data.message);
                                    app.changeAddressDrawer = false;
                                } else {
                                    app.noticeWarnings(res.data.error);
                                }
                            })
                            .catch(err => {
                                app.noticeError('哦豁！服务器出BUG了!GG，请刷新重试！');
                                console.log(err)
                            });
                    },


                    provinceChange(selectItem) {
                        app.selectAddress.selectProvince = selectItem;
                        this.cities = [];
                        this.selectAddress.selectCity = '';
                        this.selectAddress.selectCounty = '';
                        this.selectAddress.selectRegion = '';
                        this.countyEnable = true;
                        this.regionEnable = true;
                        for (let i = 0; i < this.provinces.length; i++) {
                            if (this.provinces[i].province_id === selectItem) {
                                app.selectProvinceName = this.provinces[i].province_name;
                                break;
                            }
                        }
                        axios.get('/user/getCity/' + selectItem)
                            .then(res => {
                                res.data.data.forEach((item, index) => {
                                    app.cities.push(item);
                                });
                                app.cityEnable = false;
                            })
                            .catch(err => {
                                app.noticeError('获取城市数据失败，请刷新重试！');
                                console.log(err);
                            })
                    }
                    ,
                    cityChange(selectItem) {
                        app.selectAddress.selectCity = selectItem;
                        this.counties = [];
                        this.selectAddress.selectCounty = '';
                        this.selectAddress.selectRegion = '';
                        this.regionEnable = true;
                        for (let i = 0; i < this.cities.length; i++) {
                            if (this.cities[i].city_id === selectItem) {
                                app.selectCityName = this.cities[i].city_name;
                                break;
                            }
                        }
                        axios.get('/user/getCounty/' + selectItem)
                            .then(res => {
                                res.data.data.forEach((item, index) => {
                                    app.counties.push(item);
                                });
                                app.countyEnable = false;
                            })
                            .catch(err => {
                                app.noticeError('获取城镇数据失败，请刷新重试！');
                                console.log(err);
                            })
                    }
                    ,
                    countyChange(selectItem) {
                        app.selectAddress.selectCounty = selectItem;
                        this.regions = [];
                        this.selectAddress.selectRegion = '';
                        for (let i = 0; i < this.counties.length; i++) {
                            if (this.counties[i].county_id === selectItem) {
                                app.selectCountyName = this.counties[i].county_name;
                                break;
                            }
                        }

                        axios.get('/user/getRegion/' + selectItem)
                            .then(res => {
                                res.data.data.forEach((item, index) => {
                                    app.regions.push(item);
                                });
                                app.regionEnable = false;
                            })
                            .catch(err => {
                                app.noticeError('获取地区数据失败，请刷新重试！');
                                console.log(err);
                            })
                    }
                    ,
                    regionChange(selectItem) {
                        app.selectAddress.selectRegion = selectItem;
                        for (let i = 0; i < this.regions.length; i++) {
                            if (this.regions[i].town_id === selectItem) {
                                app.selectRegionName = this.regions[i].town_name;
                                break;
                            }
                        }
                    }
                    ,
                    detail(id) {
                        window.location = '/detail/' + id;
                    }
                    ,
                    noticeWarning(message) {
                        app.$notify.warning({
                            title: '提示',
                            message: message,
                        });
                    }
                    ,
                    noticeSuccess(message) {
                        app.$notify.success({
                            title: '提示',
                            message: message,
                        });
                    }
                    ,
                    noticeWarnings(messages) {
                        messages.forEach((item, index) => {
                            setTimeout(function () {
                                app.$notify.warning({
                                    title: '提示',
                                    message: item,
                                });
                            }, 1)
                        })
                    }
                    ,
                    noticeError(message) {
                        app.$notify.error({
                            title: '提示',
                            message: message,
                        });
                    }
                }
            })
        ;
    </script>
@endsection
